import { computed, observable } from 'mobx';
import { observer } from "mobx-react";
import * as React from 'react';
import * as ReactDOM from 'react-dom';

interface TodoProps { initialTodos: string[] }

@observer
export class TodoList extends React.Component<TodoProps, {}>{
    @observable todos: Record<string, boolean> = {}
    todoRef = React.createRef<HTMLInputElement>()
    constructor(p: TodoProps) {
        super(p);
        for (let t of p.initialTodos)
            this.todos[t] = false;
    }

    @computed get pendingTodos() {
        return Object.keys(this.todos).filter(todo => this.todos[todo] === false)
    }

    @computed get doneTodos() {
        return Object.keys(this.todos).filter(todo => this.todos[todo] === true)
    }

    addTodo = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        this.todos[this.todoRef.current.value] = false
        this.todoRef.current.value = ''
    }
    toggleTodo = (todo: string) => {
        this.todos[todo] = !this.todos[todo]
    }

    renderTodo = (done: boolean) => (todo: string) => (
        <div key={todo} onClick={() => { this.toggleTodo(todo) }} >{done ? "ok" : "no"} {todo}</div>
    )

    render() {
        return (
            <form onSubmit={this.addTodo}>
                {this.pendingTodos.map(this.renderTodo(false))}
                {this.doneTodos.map(this.renderTodo(true))}
                <br />
                <input ref={this.todoRef} />
                <button>Add todo</button>
            </form>
        )
    }
}

export function RenderTodo_ClassStore2() {
    ReactDOM.render(
        <TodoList
            initialTodos={['Introduce MobX in React', 'Make a great app with MobX']}
        />,
        document.getElementById("app"))
}
